package com.github.andy0106.kersstjtl.files;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;

public class Dir {
    private String name;
    private String path;
    private transient Path paths;
    private List<Dir> children_dir = new ArrayList<>();
    private List<File> children_file = new ArrayList<>();

    public Dir(String name, String path) {
        this.name = name;
        this.path = path;
        this.paths = Paths.get(path, name);
    }

    public Dir(Path paths) {
        this(paths.getFileName().toString(), paths.getParent().toString());
    }

    public boolean walk() {
        if (!isExists()) return false;
        try {
            Stream<Path> lists = Files.list(paths);
            lists.forEach(path1 -> {
                if (Files.isDirectory(path1)) {
                    Dir sub_dir = new Dir(path1);
                    sub_dir.walk();
                    children_dir.add(sub_dir);
                } else {
                    children_file.add(new File(path1));
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    public boolean create() {
        try {
            Files.createDirectories(this.paths);
        } catch (IOException e) {
            return false;
        }
        return true;
    }

    public boolean isExists() {
        return Files.isDirectory(paths);
    }

    @Override
    public String toString() {
        return paths.toString();
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPath() {
        return path;
    }

    public void setPath(String path) {
        this.path = path;
    }

    public Path getPaths() {
        return paths;
    }

    public void setPaths(Path paths) {
        this.paths = paths;
    }

    public List<Dir> getChildren_dir() {
        return children_dir;
    }

    public void setChildren_dir(List<Dir> children_dir) {
        this.children_dir = children_dir;
    }

    public List<File> getChildren_file() {
        return children_file;
    }

    public void setChildren_file(List<File> children_file) {
        this.children_file = children_file;
    }

    public File getFile(String name) {
        if (!isExists()) return null;
        for (File file : children_file) {
            if (file.getName().equals(name)) return file;
        }
        return null;
    }

    public Dir getDir(String name) {
        if (!isExists()) return null;
        for (Dir dir : children_dir) {
            if (dir.getName().equals(name)) return dir;
        }
        return null;
    }
}
